package com.dr.controller.index;

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.dr.entity.User;
import com.dr.service.LoginService;
import com.dr.service.UserService;
import com.dr.util.ImageVerificationCode;
import com.dr.util.LayUiResult;

@Controller
@RequestMapping("/index/")
public class LoginController {

	@Autowired
	private LoginService loginService;
	@Autowired
	private UserService userService;
	

	@RequestMapping(value  = "/findLogin.do",method = RequestMethod.POST)
	public String find(User userinfo, Model model, HttpSession session,String yzm) {
		String tu=(String)session.getAttribute("yzmtext");
		if(!yzm.equalsIgnoreCase(tu)) {
			//验证码输入错误
			model.addAttribute("msg","验证码输入错误");
			return "login.jsp";
		}
		User user=loginService.find(userinfo);
		if (user == null) {
			model.addAttribute("msg", "手机号或密码输入错误");
			return "login.jsp";
		}
		session.setAttribute("loginUser", user);
		return "AllIndexProduct.do";
	}
	@RequestMapping("/getVerifiCode.do")
    @ResponseBody
    public void getVerifiCode(HttpServletRequest request, HttpServletResponse response) throws IOException {
        /*
             1.生成验证码
             2.把验证码上的文本存在session中
             3.把验证码图片发送给客户端
             */
        ImageVerificationCode ivc = new ImageVerificationCode();     //用我们的验证码类，生成验证码类对象
        BufferedImage image = ivc.getImage();  //获取验证码
        request.getSession().setAttribute("yzmtext", ivc.getText()); //将验证码的文本存在session中
        ivc.output(image, response.getOutputStream());//将验证码图片响应给客户端
    }
	/**
	 * 添加用户
	 * @param u
	 * @param model
	 * @param bindingResult
	 * @return
	 */
	@RequestMapping("/insertIndexUser.do")
	public String insertIndexUser(@Valid User u, Model model,BindingResult br) {
		if (br.hasErrors()) {
			// 校验不通过，跳转到注册页面
			model.addAttribute("msg", "你输入的数据格式有误，请重新输入");
			return "reg.jsp";
		}else {
			int num = userService.insertIndexUser(u);
		}
		return "login.jsp";
	}
}